/**
 * @file: 关联角色
 * @author: Lengxx
 * @date: 2024-06-20
 */
<template>
  <BasicModal
  title="关联角色"
  v-bind="$attrs"
  @register="register"
  @ok="onModalSubmit"
  >
    <Spin :spinning="loading">
      <Form 
      :labelCol="{ style: { width: '100px' } }"
      >
        <FormItem label="用户名" >
          <Input v-model:value="formState.username" disabled />
        </FormItem>
        <FormItem label="昵称" >
          <Input v-model:value="formState.nickname" disabled />
        </FormItem>
        <FormItem label="关联角色" >
          <ICheckBoxGroup 
          :items="checkboxItems" 
          :default-value="formState.defaultRole" 
          @change="onCheckboxChange" ></ICheckBoxGroup>
        </FormItem>
      </Form>
    </Spin>
  </BasicModal>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue'
import { Spin, Form, FormItem, Input } from 'ant-design-vue'
import { getRoleList } from '@/api/permisson/role'
import { IUserInfo, updateUserInfo } from '@/api/user'
import { BasicModal, useModalInner } from '@/components/Modal'
import { useRequest } from '@vben/hooks'
import { ICheckBoxGroup } from '@/components/ICheckBox'

const { loading, data, runAsync } = useRequest(getRoleList)

const emits = defineEmits(['submit'])

const formState = reactive({
  id: '',
  username: '',
  nickname: '',
  role: '',
  defaultRole: []
});

const { resetFields } = Form.useForm(formState);

const outData = ref<IUserInfo>();

const [register] = useModalInner(data => {
  runAsync();
  if (data) {
    resetFields();
    formState.username = data.username;
    formState.nickname = data.nickname;
    formState.defaultRole = data.role.split(',');
    formState.role = data.role;
    formState.id = data.id;
    outData.value = data;
  }
})

const checkboxItems = computed(() => {
  return data.value.map(item => ({...item, label: item.name, value: item.id }))
})

function onCheckboxChange(data: string[]) {
  formState.role = data.join(',');
}

/** 绑定角色提交 */
async function onModalSubmit() {
  const { id, role } = formState;
  if (outData.value) {
    const { phone, nickname, avatar } = outData.value;
    const data: IUserInfo = {
      id,
      role,
      nickname,
      phone,
      avatar
    }
    await updateUserInfo(data);
    emits('submit');
  }
}

</script>

